﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Text.RegularExpressions;
using System.Windows.Ink;
using System.Windows.Controls.Primitives;
using System.Globalization;
using TouchUmlUI;
using Parser;

using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;


namespace UCUTextRecognizer
{
    /// <summary>
    /// Interaction logic for HandWrite.xaml
    /// </summary>
    /// 

    
    public partial class HandWrite : UserControl
    {
        private InkAnalyzer analyzer_PL;
        private InkAnalyzer analyzer_EN;
        private InkAnalyzer analyzer_NO;
        private AnalysisStatus status;
        private bool canvas_focus;

        private String[] hints = { "int ", "__int8 ", "__int16", "__int32", 
                                       "__int64", "short",  "long", "longlong", 
                                       "unsigned int", "unsigned __int8", "unsigned __int16", 
                                       "unsigned __int32", "unsigned __int64", "bool", "char",
                                       "signed char", "unsigned char", "short", "unsigned short",
                                       "long", "unsigned long", "long long", "unsigned long long", 
                                        "enum", "float", "double", "long double", "wchar_t", "boolean", "object",
                                        "()"
                                   };

        static private bool lang_PL = false;
        static private bool lang_EN = false;
        static private bool lang_NO = false;
        static private bool languages_checked = false;
        private int currentLanguage;
        private bool preserveExisting;
        public const int textMargin = 10;
        public const int textHeight = 61;
        public const int upperMargin = 35;
        public const int lowerMargin = 25;
        public const int cutY = 50;
        public InkCanvasEditingMode editingMode;


        static void detectLanguages() 
        {
            InkAnalyzer language_detector = new InkAnalyzer();
            String test_letter = "a";
            String test;

            ArrayList lista = HandWrite.deserialize(test_letter);
            Stroke firstStroke = (Stroke)lista[0]; 

            // Check for PL
            language_detector.AddStroke(firstStroke , PL);
            language_detector.SetStrokeLanguageId(firstStroke, PL);
            language_detector.Analyze();
            test = language_detector.GetRecognizedString();
            if (test == test_letter)
                lang_PL = true;
            language_detector.RemoveStroke(firstStroke);

            // Check for EN
            language_detector.AddStroke(firstStroke, EN);
            language_detector.SetStrokeLanguageId(firstStroke, EN);
            language_detector.Analyze();
            test = language_detector.GetRecognizedString();
            if (test == test_letter)
                lang_EN = true;
            language_detector.RemoveStroke(firstStroke);

            // Check for NO
            AnalysisHintNode ld_hint = language_detector.CreateAnalysisHint();
            ld_hint.Factoid = "NONE";
            //ld_hint.CoerceToFactoid = true;
            ld_hint.Name = "language_detector";
            ld_hint.Location.MakeInfinite();

            language_detector.AddStroke(firstStroke, NO);
            language_detector.Analyze();
            test = language_detector.GetRecognizedString();
            if (test == test_letter)
                lang_NO = true;
    
            }


        // bind
        Diagram.Element element;
        OurCanvas mcanvas;
        UMLObj umlObj;
        OurTab tab;
        Diagram.Asocjacja.KoncowkaAsocjacji koncowka;
        bool from;

        const int PL = 0x0415;
        const int EN = 0x0809;
        const int NO = 0x0;


        public void bindWithKoncowka(Diagram.Asocjacja.KoncowkaAsocjacji konc, bool from,UMLObj umlObj)
        {
            this.umlObj = umlObj;
            this.from = from;
            koncowka = konc;
            element = null;
            mcanvas = null;
            umlObj = null;
            this.tab = null;
        }

        public void bindWithTab(OurTab tab)
        {
            koncowka = null;
            element = null;
            mcanvas = null;
            umlObj = null;
            this.tab = tab;
        }

        public void bindWithObject(Diagram.Element element, OurCanvas mcanvas, UMLObj umlObj)
        {
            koncowka = null;
            this.tab = null;
            this.element = element;
            this.mcanvas = mcanvas;
            this.umlObj = umlObj;
        }

        public HandWrite()
        {
            if (languages_checked == false)
                detectLanguages();
            InitializeComponent();
            Start();
            canvas_focus = false;
            
            currentLanguage = NO;
            canvas.Background = new SolidColorBrush(Color.FromArgb(100, 255, 255, 255));
            
            preserveExisting = false;
            this.Loaded += new RoutedEventHandler(HandWrite_Loaded);
            this.SizeChanged += new SizeChangedEventHandler(HandWrite_SizeChanged);
            this.PreviewMouseMove += new MouseEventHandler(HandWrite_MouseMove);
            changer.PreviewMouseMove += HandWrite_MouseMove;
            //canvas.MouseMove += new MouseEventHandler(canvas_MouseMove);            
            CaptureStylus();
            CaptureMouse();
            SignalR.windowParent.SelectMode.IsEnabled = false;
            SignalR.windowParent.EraseByPointMode.IsEnabled = false;
            SignalR.windowParent.EraseByStrokeMode.IsEnabled = false;
            SignalR.windowParent.DrawMode.IsEnabled = false;
            SignalR.windowParent.EditMode.IsEnabled = false;
            SignalR.windowParent.FreeMode.IsEnabled = false;
            if (SignalR.windowParent.active_canvas.Children.Contains( SignalR.windowParent.hintbox))
            {
                if (!SignalR.windowParent.hintbox.isHiding())
                {
                    SignalR.windowParent.hintbox.Hide(SignalR.windowParent.active_canvas);
                    SignalR.windowParent.hintbox = null;
                }
            }

        }

        void HandWrite_MouseMove(object sender, MouseEventArgs e)
        {/*
            Point p = e.GetPosition(this);
            Console.WriteLine(p+""+" na "+this.ActualWidth+"x"+this.ActualHeight);
            if (p.X > canvas.ActualWidth - 10)
            {
                canvas.Width = p.X + 50;
                this.Width = p.X + 50;
            }

            if (p.Y > canvas.ActualHeight - 10)
            {
                canvas.Height = p.Y + 50;
                this.Height = p.Y + 50;
            }*/
        }

        void canvas_MouseMove(object sender, MouseEventArgs e)
        {            
                
        }

        void HandWrite_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            double vx = InkCanvas.GetLeft(this) + this.ActualWidth;
            double vy = InkCanvas.GetTop(this) + this.ActualHeight;

            if (InkCanvas.GetLeft(this) < 10)
            {
                InkCanvas.SetLeft(this, 10);
            }

            if (InkCanvas.GetTop(this) < 10)
            {
                InkCanvas.SetTop(this, 10);
            }

            Console.WriteLine("vx: " + vx + " vy: " + vy);
            if (vx > SignalR.windowParent.active_canvas.ActualWidth)
            {
                SignalR.windowParent.active_canvas.Width = vx + 10;
                //SignalR.windowParent.sv.ScrollToRightEnd();
            }
            if (vy > SignalR.windowParent.active_canvas.ActualHeight)
            {
                SignalR.windowParent.active_canvas.Height = vy += 10;
                //SignalR.windowParent.sv.ScrollToBottom();
            }
        }

        void HandWrite_Loaded(object sender, RoutedEventArgs e)
        {
            canvas.Strokes.Clear();
            setExistingText(changer.Text);
            
            changer.Focus();
            canvas_focus = false;

            // NO Dictionary
            AnalysisHintNode hintNode_NO = analyzer_NO.CreateAnalysisHint();
            hintNode_NO.Factoid = "NONE";
            hintNode_NO.Location.MakeInfinite();
            hintNode_NO.SetWordlist(hints);
            hintNode_NO.Name = "Primitivies NO";

            editingMode = SignalR.windowParent.active_canvas.EditingMode; 
            SignalR.windowParent.active_canvas.EditingMode = InkCanvasEditingMode.None;                
        }


        private String deleteEnters(String text)
        {
            string resultString = null;
            resultString = Regex.Replace(text, @"\n", "");

            return resultString;
        }


        public void setHint()
        {

            // PL
            AnalysisHintNode hintNode_PL = analyzer_PL.CreateAnalysisHint();
            hintNode_PL.Location.MakeInfinite();
            hintNode_PL.SetWordlist(hints);
            hintNode_PL.Name = "Primitivies PL";

            // PL
            AnalysisHintNode hintNode_EN = analyzer_EN.CreateAnalysisHint();
            hintNode_EN.Location.MakeInfinite();
            hintNode_EN.SetWordlist(hints);
            hintNode_EN.Name = "Primitivies EN";
        }

        private String correctText(String txt)
        {
            bool cnt = txt.Contains("(");
            if (cnt == false)
            {
                for (int i = 1; i < txt.Length; i++)
                {
                    if (txt[i] == ')')
                    {
                        StringBuilder sb = new StringBuilder(txt);
                        sb[i - 1] = '(';
                        txt = sb.ToString();
                    }
                }
            }
            return txt;
        }

        public bool Recognize()
        {
            String str = getResult();
            if (str == null)
            {
                //MessageBox.Show("Błąd rozpoznawania: Nie rozpoznano żadnego tekstu!", "Uwaga!", MessageBoxButton.OK, MessageBoxImage.Error);
                return true;
            }            

            if (tab != null)
            {
                tab.setTitle(str);
                tab.getTabbedControl().Refresh();
                SignalR.windowParent.fillTabs();
                return true;
            }

            if (koncowka != null)
            {
                if (from)
                {
                    ((Diagram.Asocjacja)umlObj.guml.obj_uml)[0].Tekst = str;
                }
                else 
                {
                    ((Diagram.Asocjacja)umlObj.guml.obj_uml)[1].Tekst = str;
                }
                ((AssociationObj)umlObj).setTextBlockPositions();
                ((AssociationObj)umlObj).Refresh();
                return true;
            }

            if (element is Diagram.Akcja)
            {
                (element as Diagram.Akcja).Nazwa = str;                
                (umlObj as AkcjaObj).updateDependencyProperties();
            }
            else if (element is Diagram.Aktor)
            {
                (element as Diagram.Aktor).Nazwa = str;
            }
            else if (element is Diagram.Notatka)
            {
                (element as Diagram.Notatka).Tekst = str;
            }
            else if (element is Diagram.Klasa)
            {
                try
                {
                    (element as Diagram.Klasa).Nazwa = str;
                }
                catch (ModelUML.NameException e)
                {
                    MessageBoxResult res = MessageBox.Show("Istnieje już klasa o tej samej nazwie!\r\nCzy chcesz połączyć te klasy?", "Uwaga!", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (res == MessageBoxResult.Yes)
                    {
                        e.Scal();
                    }                    
                }
            }
            else if (element is Diagram.Interfejs)
            {
                (element as Diagram.Interfejs).Nazwa = str;
            }
            else if (element is Diagram.Atrybut)
            {
                if ((element as Diagram.Atrybut).Nazwa.CompareTo("CHANGE") == 0)
                {
                    try
                    {
                        Parse p = new Parse();
                        Diagram.Element nElem = p.konwertujNaModel(p.parsujAtrybut(str));
                        String helpstr = "";
                        helpstr = "Format rozpoznawania atrybutu to: zasięg nazwa : typ [krotność]";
                        if (nElem == null) throw new Exception("Nie można sparsować \"" + str + "\" jako atrybutu!\r\n"+helpstr);
                        if (umlObj.getType() == typeof(KlasaObj))
                        {
                            KlasaObj kObj = umlObj as KlasaObj;
                            ((Diagram.Klasa)kObj.guml.obj_uml).DodajAtrybut(nElem as Diagram.Atrybut);
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message, "Uwaga!", MessageBoxButton.OK, MessageBoxImage.Error);
                        return false;
                    }
                }
                else
                {
                    Parse p = new Parse();
                    Diagram.Element nElem = p.konwertujNaModel(p.parsujAtrybut(str));
                    String helpstr = "";
                    helpstr = "Format rozpoznawania atrybutu to: zasięg nazwa : typ [krotność]";
                    if (nElem == null) throw new Exception("Nie można sparsować \"" + str + "\" jako atrybutu\r\n!"+helpstr);
                    if (umlObj.getType() == typeof(KlasaObj))
                    {
                        ((Diagram.Atrybut)element).Nazwa = nElem.Nazwa;
                        ((Diagram.Atrybut)element).Typ.Nazwa = ((Diagram.Atrybut)nElem).Typ.Nazwa;
                        ((Diagram.Atrybut)element).Visibility = nElem.Visibility;
                    }
                }
            }
            else if (element is Diagram.Operacja)
            {
                String helpstr = "";
                helpstr = "Format rozpoznawania metody to: zasięg nazwa(lista_parametrów):typ_zwracany\r\nlista_atrybutów, format: nazwa:typ oddzielone przecinkami.";
                if ((element as Diagram.Operacja).Nazwa.CompareTo("CHANGE") == 0)
                {                    
                    try
                    {
                        Parse p = new Parse();
                        Diagram.Element nElem = p.konwertujNaModel(p.parsujMetode(str));                        
                        if (nElem == null) throw new Exception("Nie można sparsować \"" + str + "\" jako metody!\r\n"+helpstr);
                        if (umlObj.getType() == typeof(KlasaObj))
                        {
                            KlasaObj kObj = umlObj as KlasaObj;
                            ((Diagram.Klasa)kObj.guml.obj_uml).DodajOperacje(nElem as Diagram.Operacja);
                        }
                        else if (umlObj.getType() == typeof(InterfejsObj))
                        {
                            KlasaObj kObj = umlObj as KlasaObj;
                            ((Diagram.Interfejs)kObj.guml.obj_uml).DodajOperacje(nElem as Diagram.Operacja);
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message, "Uwaga!", MessageBoxButton.OK, MessageBoxImage.Error);       
                        return false;
                    }
                }
                else
                {
                    Parse p = new Parse();
                    Diagram.Element nElem = p.konwertujNaModel(p.parsujMetode(str));
                    if (nElem == null) throw new Exception("Nie można sparsować \"" + str + "\" jako metody!\r\n"+helpstr);
                    if ((umlObj.getType() == typeof(KlasaObj)) || (umlObj.getType()==typeof(InterfejsObj)))
                    {
                        KlasaObj kObj = umlObj as KlasaObj;
                        ((Diagram.Operacja)element).Nazwa = nElem.Nazwa;
                        ((Diagram.Operacja)element).Typ = ((Diagram.Operacja)nElem).Typ;
                        ((Diagram.Operacja)element).Visibility = nElem.Visibility;
                        ((Diagram.Operacja)element).UsunAtrybuty();
                        for (int i = 0; i < ((Diagram.Operacja)nElem).IloscAtrybutow; i++)
                        {
                            ((Diagram.Operacja)element).DodajAtrybut(((Diagram.Operacja)nElem).GetAtrybut(i));
                        }

                    }
                }
            }
            umlObj.Refresh();
            umlObj.updateDependencyProperties();            
            return true;
        }

    public void Start()
        {
            analyzer_PL = new InkAnalyzer();
            analyzer_EN = new InkAnalyzer();
            analyzer_NO = new InkAnalyzer();

            //analyze.Click += new System.Windows.RoutedEventHandler(analyze_Click);

            //canvas.StylusOutOfRange += new System.Windows.Input.StylusEventHandler(B_recognize_Click);
            canvas.Strokes.StrokesChanged += new StrokeCollectionChangedEventHandler(Strokes_StrokesChanged);
    }
    
    public void setExistingText(String existingText)
    {
        existingText = existingText.Trim();

        canvas.Strokes.Clear();
        setText(existingText);
        preserveExisting = true;
        setChangerText(existingText);
    }


    private void Serialize(bool save)
    {
        String litera = getResult();

        String path ="chars\\" + changer.Text;

        ArrayList lista = new ArrayList();

        IEnumerator<Stroke> EmpEnumerator = canvas.Strokes.GetEnumerator();
        EmpEnumerator.Reset();

        while (EmpEnumerator.MoveNext())
        {
            Stroke temp = (Stroke)EmpEnumerator.Current;
            DiagramStroke ds = new DiagramStroke();
            ds.fromStroke(temp);
            lista.Add(ds);
        }



        if (save == false)
            setChangerText(litera + ".char");
        else
        {
            
            FileStream fs = new FileStream(path, FileMode.Create);
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(fs, lista);
            fs.Close();
            setChangerText("| " + path + " |");
        }
    }

    private void setText(String tekst)
    {
        int i;
        ArrayList linie = new ArrayList();
        String linia = "";

        int check_x = 0;

        for (i = 0; i < tekst.Length; i++)
        {
                

                if (Char.IsUpper(tekst, i) || tekst.Substring(0,1) == " ")
                    check_x += upperMargin;
                else
                    check_x += lowerMargin;
                
                linia += tekst.Substring(i, 1); ;

                if (check_x > ActualWidth - 5 * textMargin || (i == tekst.Length - 1))
                {
                    linie.Add(linia);
                    linia = "";
                    check_x = 0;
                }           
        }
            int check_x_over = linie.Count * textHeight + (linie.Count + 1) * textMargin;
            if (check_x_over > ActualHeight)
                Height = check_x_over;   

            Point beginPoint = new Point();

            beginPoint.X = textMargin;
            beginPoint.Y = Math.Floor((Height - ((double)linie.Count * (double)textHeight + (double)(linie.Count - 1) * (double)textMargin)) / 2.0);

            int offset_x = 0;
            int factor_y = 1;

            String litera_out;
            int j;
            foreach (String line in linie)
            {
                for (j = 0; j < line.Length; j++)
                {
                    litera_out = line.Substring(j, 1);
                    ArrayList stroki_litery = deserialize(litera_out);
                    
                    IEnumerator Enumerator = stroki_litery.GetEnumerator();
                    Enumerator.Reset();
                    while (Enumerator.MoveNext())
                    {
                        Stroke cur = (Stroke)Enumerator.Current;
                        StrokeCollection kolekcja = new StrokeCollection();
                        kolekcja.Add(cur);

                        TranslateStrokes(kolekcja, beginPoint.X + offset_x, beginPoint.Y + factor_y * textHeight + factor_y * textMargin - 61);
                        canvas.Strokes.Add(kolekcja);
                    }
                    if (Char.IsUpper(litera_out, 0))
                            offset_x += upperMargin;
                        else
                            offset_x += lowerMargin;
                }
                offset_x = 0;
                factor_y++;
            }
        }
    

    // Helper method that transletes the specified strokes.
    void TranslateStrokes(StrokeCollection strokes,
                          double x, double y)
    {
        Matrix mat = new Matrix();
        mat.Translate(x, y);
        strokes.Transform(mat, false);
    }

    private void setChangerText(String text)
    {        
        changer.Text = deleteEnters(correctText(text));
    }

    static private ArrayList deserialize(String litera)
    {

        if(System.Char.IsLetter(litera,0) && System.Char.IsLower(litera,0))
            litera = litera.Substring(0,1).ToUpper() + "_l";

        if (litera == ":")
            litera = "dwukropek";
        else if (litera == "~")
            litera = "tylda";
        else if (litera == "`")
            litera = "gorny_apostrof";
        else if (litera == "*")
            litera = "gwiazdka";
        else if (litera == ".")
            litera = "kropka";
        else if (litera == "?")
            litera = "znak_zapytania";
        else if (litera == "!")
            litera = "wykrzyknik";
        else if (litera == ";")
            litera = "srednik";
        else if (litera == "<")
            litera = "trojkatny_lewy";
        else if (litera == ">")
            litera = "trojkatny_prawy";
        else if (litera == "/")
            litera = "slash";
        else if (litera == "\\")
            litera = "backslash";
        else if (litera == "|")
            litera = "pion";
        else if (litera == "\"")
            litera = "cudzyslow_gorny";
        else if (litera == "„")
            litera = "cudzyslow_dolny";

        String path = "chars\\" + litera + ".char";

        if (File.Exists(path) == false)
            return new ArrayList();

        FileStream fs = new FileStream(path, FileMode.Open);
        BinaryFormatter formatter = new BinaryFormatter();

        ArrayList lista = new ArrayList();
        ArrayList ret = new ArrayList();

        lista = (ArrayList)formatter.Deserialize(fs);

        IEnumerator EmpEnumerator = lista.GetEnumerator();
        EmpEnumerator.Reset();

        StrokeCollection s_kolekcja = new StrokeCollection();

        DiagramStylusPoint dsp;
        while (EmpEnumerator.MoveNext())
        {
            StylusPointCollection sp_kolekcja = new StylusPointCollection();
            DiagramStroke temp = (DiagramStroke)EmpEnumerator.Current;

            IEnumerator listaEnumerator = lista.GetEnumerator();
            listaEnumerator.Reset();
            while (listaEnumerator.MoveNext())
            {
                DiagramStroke ds = (DiagramStroke)EmpEnumerator.Current;

                IEnumerator dss_Enumerator = ds.lista.GetEnumerator();
                dss_Enumerator.Reset();

                while (dss_Enumerator.MoveNext())
                {
                    dsp = (DiagramStylusPoint)dss_Enumerator.Current;
                    sp_kolekcja.Add(dsp.toStylusPoint());
                }

                Stroke stroke = new Stroke(sp_kolekcja);
                ret.Add(stroke);
                break;
            }


        }
        fs.Close();
        return ret;
    }



        void Strokes_StrokesChanged(object sender, StrokeCollectionChangedEventArgs e)
        {
            if (e.Added.Count > 0)
            {
                // NO
                analyzer_NO.AddStrokes(e.Added);
                analyzer_NO.SetStrokesType(e.Added, StrokeType.Writing);
                //analyzer_NO.SetStrokesLanguageId(e.Added, NO2);

                // PL
                analyzer_PL.AddStrokes(e.Added);
                analyzer_PL.SetStrokesType(e.Added, StrokeType.Writing);
                analyzer_PL.SetStrokesLanguageId(e.Added, PL);

                // EN
                analyzer_EN.AddStrokes(e.Added);
                analyzer_EN.SetStrokesType(e.Added, StrokeType.Writing);
                analyzer_EN.SetStrokesLanguageId(e.Added, EN);
            }

            if (e.Removed.Count > 0)
            {
                analyzer_PL.RemoveStrokes(e.Removed);
                analyzer_EN.RemoveStrokes(e.Removed);
                analyzer_NO.RemoveStrokes(e.Removed);
            }
            
        }

        private void AnalyzeText()
        {

            if (currentLanguage == PL)
            {
                status = analyzer_PL.Analyze();

                //changeStatusBar(status.Successful.ToString());

                if (status != null && status.Successful == true)
                    setChangerText(analyzer_PL.GetRecognizedString());
            }

            if (currentLanguage == EN)
            {
                status = analyzer_EN.Analyze();

                //changeStatusBar(status.Successful.ToString());

                if (status != null && status.Successful == true)
                    setChangerText(analyzer_EN.GetRecognizedString());
            }

            if (currentLanguage == NO)
            {
                status = analyzer_NO.Analyze();
                ArrayList test = new ArrayList();
                test.Add(status.Warnings);

                //changeStatusBar(status.Successful.ToString());

                if (status != null && status.Successful == true)
                    setChangerText(analyzer_NO.GetRecognizedString());
            }
        }

        public String getResult()
        {
            if (canvas_focus == true)
                AnalyzeText();
            if (changer.Text == "")
                return null;
            else
                return changer.Text;
        }


        private void B_recognize_Click(object sender, RoutedEventArgs e)
            {
            preserveExisting = true;
            AnalyzeText();
            
            //if (temp != null)
                //setChangerText(temp);
            
                //Serialize(true);
            }

        private void B_erase_Click(object sender, RoutedEventArgs e)
            {
            canvas.Strokes.Clear();
            setChangerText("");
            }

        private void B_language_EN_Click(object sender, RoutedEventArgs e)
            {
            this.currentLanguage = PL;
            B_language_EN.Visibility = Visibility.Hidden;
            B_language_PL.Visibility = Visibility.Visible;
            B_language_NO.Visibility = Visibility.Hidden;

            //setExistingText(changer.Text);
                //Serialize(false);
            }

        private void B_language_PL_Click(object sender, RoutedEventArgs e)
            {
            this.currentLanguage = NO;
            B_language_EN.Visibility = Visibility.Hidden;
            B_language_PL.Visibility = Visibility.Hidden;
            B_language_NO.Visibility = Visibility.Visible;
            }

        private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {

        }

        private void changer_TextChanged_2(object sender, TextChangedEventArgs e)
        {

            if (preserveExisting == true)
                preserveExisting = false;
            else
            {
                canvas.Strokes.Clear();
                setText(changer.Text);
            }
        }

        private void changer_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Return)
            {
                SignalR.windowParent.checkRecognize();
            }                            
        }

        private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (e.HeightChanged)
                this.Height = e.NewSize.Height;
            if (e.WidthChanged)
                this.Width = e.NewSize.Width;
        }

        private void B_language_NO_Click(object sender, RoutedEventArgs e)
        {
            this.currentLanguage = EN;
            B_language_EN.Visibility = Visibility.Visible;
            B_language_PL.Visibility = Visibility.Hidden;
            B_language_NO.Visibility = Visibility.Hidden;
        }

        private void canvas_GotFocus(object sender, RoutedEventArgs e)
        {
            canvas_focus = true;
        }

        private void changer_GotFocus(object sender, RoutedEventArgs e)
        {
            canvas_focus = false;
        }

    }
}
